/* 
    自动计算瀑布流位置，每个card使用的是绝对定位，需计算每个card的偏移量就行
*/
//把父级名称和列数传到方法里
const computeWaterFallFlow = (ref, colums = 2) => {
    let resizeListener = null

    //卡片X轴偏移量 = card宽度 *1 + card边距总和
    const computeCard = () => {
        const cards = ref.children
        const winWidth = window.innerWidth //获取当前视域宽度
        const margin = Math.round(winWidth * 0.015) // 计算出card的边距
        const cardWidth = Math.floor((winWidth - (colums + 1) * margin) / colums) //计算出每个card的宽度

        const topList = new Array(colums).fill(0) //记录每一列当前顶部的距离

        //给每个card赋予宽度，因为card中的img高度会随宽度自适应，所以每个card高度会自适应
        for (let i = 0; i < cards.length; i++) {
            cards[i].style.width = cardWidth + 'px'
        }
        //计算每个card的位置偏移
        for (let i = 0; i < cards.length; i++) {
            //判断高度，谁高插谁
            let min = Math.min(...topList)
            const minColum = topList.indexOf(min)

            //计算出card偏移量
            let left = margin * (minColum + 1) + cardWidth * minColum
            let top = min + margin
            cards[i].style.transform = `translate(${left}px,${top}px)`
            topList[minColum] += cards[i].clientHeight + margin
        }
        ref.style.height = Math.max(...topList) + margin + 'px'
    }
    computeCard()

    //监听
    if (!resizeListener) {
        resizeListener = window.addEventListener("resize", () => {
            computeCard()
        })
    }
}

export default computeWaterFallFlow